<?php defined('BASEPATH') OR exit('No direct script access allowed');

if ( ! class_exists('Controller'))
{
	class Controller extends CI_Controller {}
}

class Client extends Controller {
	var $perpage = 12;
		public function __construct() {
		parent::__construct();
		if (!$this->ion_auth->logged_in()) redirect('auth/login/' . str_replace("/", ".", $_SERVER['REQUEST_URI']));
		}

		//redirect if needed, otherwise display the user list
	function index() {
		$data['crumps'] = "<a href='/'>Главная</a> &raquo; <a href='/client/'>Личный кабинет</a>";
		//$this->layout->view('client/index', $data);
		$this->orders();
	}
	function profile() {
		$this->ion_auth_model->edit();
	}
	function orders() {
		$data['crumps'] = "<a href='/'>Главная</a> &raquo; <a href='/client/'>Личный кабинет</a>";
		$data['from'] = $from = $this->input->get('from', true);
		$status = $this->input->get('status', true);
		if ($from == "") $from = 0;
		$user = $this->ion_auth->get_user();
		$this->db->select()->from('orders')->where('order_user', $user->id)->limit($this->perpage, $from)->order_by('order_date', 'desc');
//		if ($status !== false) $this->db->where('order_status', $status); else {
//			$this->db->where('order_status > 1')->or_where('order_status < 0');
//		}
		$data['pages'] = $pages = $this->db->get()->result_array();
		/* pagination */
		$this->db->select()->from('orders')->where('order_user', $user->id);
//		if ($status !== false) $this->db->where('order_status', $status); else {
//			$this->db->where('order_status > 1')->or_where('order_status < 0');
//		}
		$count = $this->db->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('client/orders/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/client/orders/';
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */
		if ($this->ion_auth->logged_in()) {
			$user = $this->ion_auth->get_user();
			$have_data['name_1'] = $user->name_1;
			$have_data['name_2'] = $user->name_2;
			$have_data['name_3'] = $user->name_3;
			$have_data['phone'] = $user->phone;
			$have_data['email'] = $user->email;
			$have_data['address_1'] = $user->address_1;
			$have_data['address_2'] = $user->address_2;
			$have_data['address_3'] = $user->address_3;
			$have_data['urname'] = $user->urname;
			$have_data['inn'] = $user->inn;
			$have_data['kpp'] = $user->kpp;
		}
		$form = new jQuickForm('simple_order_try_reg');
		$form->setLabel('Мои данные');
		$fieldset = $form->insertFieldset();
		if (!$this->ion_auth->logged_in()) $fieldset->addClass('fullregform');

		////////
		$gr = $fieldset->insertGroup()->addClass('col col2');
		$field = $gr->insertInputText('name_1')->setLabel('Фамилия')->addRuleRequired();
		$field = $gr->insertInputText('name_2')->setLabel('Имя')->addRuleRequired();
		$field = $gr->insertInputText('name_3')->setLabel('Отчество')->addRuleRequired();
		$phone = $gr->insertInputText('phone')->setLabel('Телефон');
		$phone->addRule('callback', 'Не верный формат поля', array('callback' => 'validate_phone'), HTML_QuickForm2_Rule::CLIENT);
		$phone->addRuleRequired();
		$pass = $gr->insertInputText('password');
		$pass->setLabel('Пароль')->setComment('Заполнять только если хотите поменять пароль. Не менее 8 символов и не более 20');
		$passwordRepeat = $gr->insertInputText('password2');
		$passwordRepeat->setLabel('Подтверждение пароля');
		$passwordRepeat->addRule('eq', 'Пароли не совпадают', $pass);
		////////

		////////
		$field = $fieldset->insertInputText('address_1')->setLabel('Адрес доставки')->setComment('Если Вы хотите забрать товар в нашем магазине - укажите его адрес');

		$fieldset = $form->insertFieldset();
		if (!$this->ion_auth->logged_in()) $fieldset->addClass('fullregform');


		$gr = $fieldset->insertGroup()->addClass();
		$field = $gr->insertInputText('urname')->setLabel('Юридическое название организации')->setComment('Только для юридических лиц');
		$gr = $fieldset->insertGroup()->addClass('col col2');
		$field = $gr->insertInputText('address_2')->setLabel('Юридический адрес');
		$field = $gr->insertInputText('address_3')->setLabel('Фактический адрес');
		$field = $gr->insertInputText('inn')->setLabel('ИНН');
		$field = $gr->insertInputText('kpp')->setLabel('КПП');

		if ($_SERVER["REQUEST_METHOD"] == "POST") {
			if ($form->validate()) {
				$p_data = $this->input->post();
				if($p_data['password'] == $p_data['password2']){
					$this->db->set('password',$p_data['password']);
					$this->db->where('id',$this->ion_auth->get_user()->id);
					$this->db->update('users');
				} else {
					$this->session->set_flashdata('msg', 'Пароли не совпадают');
				}
				$additional_data['name_1'] = $p_data['name_1'];
				$additional_data['name_2'] = $p_data['name_2'];
				$additional_data['name_3'] = $p_data['name_3'];
				$additional_data['first_name'] = $p_data['name_1']." ".$p_data['name_2']." ".$p_data['name_3'];

				$additional_data['phone'] = $p_data['phone'];
				$additional_data['address_1'] = $p_data['address_1'];
				$additional_data['address_2'] = $p_data['address_2'];
				$additional_data['address_3'] = $p_data['address_3'];
				$additional_data['urname'] = $p_data['urname'];
				$additional_data['inn'] = $p_data['inn'];
				$additional_data['kpp'] = $p_data['kpp'];
				$this->db->update('meta', $additional_data, array('user_id' => $this->ion_auth->get_user()->id));

				redirect('/client/');
			}  // validate form
		} // request method


		$fieldset->insertInputSubmit("Сохранить");

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($have_data));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();


		$this->layout->view('client/orders', $data);
	}
	function show($id) {
		$data['crumps'] = "<a href='/'>Главная</a> &raquo; <a href='/client/'>Личный кабинет</a> &raquo; <a href='/client/show/".$id."/'>Заказ #".$id."</a>";
		$user = $this->ion_auth->get_user();
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('orders')->where('order_user', $user->id)->where('order_id', $id)->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('client/orders');
		$this->layout->view('client/show', $data);
	}
}